// modules/Fetch.js
import React from 'react';
import { Component } from 'react';
import { postData, getData, httpGet } from 'root_path/util/http.js';

// React component
export default class Fetch extends Component{
  constructor(){
    super();
    this.state = {
      name: '',
      age: 0,
      method: ''
    }
  }

  post(){
    const param = {
      path: "/post",
      data:{name: 'alan'}
    };
    postData(param)
    .then((data) => {
      console.log(data);
      this.setState({"name": data.name, "age": data.age, "method": data.method});
    }).catch((error) => {
      console.error(error)
      alert('fetch获取数据失败, 确认是否开启了node服务器:\n'+ error);
    });
  }
  
  jsonp(){
    const param = {
      path: "/get",
      data:{name: 'alan'}
    };
    getData(param)
    .then((json) =>{
      console.log(json);
      this.setState({"name": json.name, "age": json.age, "method": json.method});
    }).catch(function(err) {
      console.log(err);
    })
  }

  get(){
    const param = {
      path: "/get",
      data:{name: 'alan'}
    };
    httpGet(param)
    .then((json) =>{
      console.log(json);
      this.setState({"name": json.name, "age": json.age, "method": json.method});
    }).catch(function(err) {
      console.log(err);
    })
  }
  render() {
    return (
      <div>
        <p>获取数据前先 npm start 启动本地node 服务器</p>
        <button onClick={this.post.bind(this)}>CORS跨域Post获取数据</button>
        <button onClick={this.jsonp.bind(this)}>Jsonp跨域Get获取数据</button>
        <button onClick={this.get.bind(this)}>同域Get获取数据</button>
        <div>name: {this.state.name}</div>
        <div>age: {this.state.age}</div>
        <div>method: {this.state.method}</div>
      </div>
    )
  }
}